package view;
import java.awt.Graphics;
import java.util.Random;
import java.util.concurrent.Semaphore;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

@SuppressWarnings("serial")
public class DieButton extends JButton {
    private final Random r = new Random();
    private Semaphore s = new Semaphore(1);
    private int dieValue = 1;

    public void setDieValue(int dieValue) {
        this.dieValue = dieValue;
    }

    public void animate(){
        BlendDiePic bdp = new BlendDiePic();
        Thread t1 = new Thread(bdp);
        t1.start();
    }

    public void paintComponent(Graphics g){
        Icon i = this.getIcon();
        if(i != null)
            this.getIcon().paintIcon(this, g, 0, 0);
    }

    private class BlendDiePic implements Runnable {

        @Override
        public void run() {
            if(s.tryAcquire()) {
                String[] dieFaces = {"img/die6.png", "img/die5.png",
                        "img/die4.png", "img/die3.png", "img/die2.png", "img/die1.png"};
                for(int i = 140; i < 150; i++) {
                    int x = r.nextInt(6);
                    setIcon(new ImageIcon(dieFaces[x]));
                    try {
                        Thread.sleep(i);
                    } catch (InterruptedException e) {
                        System.out.println("Animation thread interrupted");
                    }
                }
                setIcon(new ImageIcon("img/die"+ dieValue +".png"));
                s.release();
            }
        }
    }
}
